package io.github.junxworks.qt.config.ds;

import java.io.IOException;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;

@Configuration
@MapperScan(basePackages = { "io.github.junxworks.ep.*", "io.github.junxworks.qt.*" }, annotationClass = Mapper.class, sqlSessionTemplateRef = "mainSqlSessionTemplate")
public class MainDataSourceConfig {

	@Bean("mainDataSource")
	@ConfigurationProperties("spring.datasource.druid.main")
	public DataSource mainDataSource() throws SQLException, IOException {
		return DruidDataSourceBuilder.create().build();
	}

	@Bean(name = "mainSqlSessionFactory")
	public SqlSessionFactory mainSqlSessionFactory(@Qualifier("mainDataSource") DataSource dataSource) throws Exception {
		SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
		bean.setDataSource(dataSource);
		SqlSessionFactory factory = bean.getObject();
		org.apache.ibatis.session.Configuration config = factory.getConfiguration();
		config.setMapUnderscoreToCamelCase(true);
		config.setLazyLoadingEnabled(true);
		config.setDefaultStatementTimeout(300);
		return factory;
	}

	@Bean(name = "mainTransactionManager")
	public DataSourceTransactionManager mainTransactionManager(@Qualifier("mainDataSource") DataSource dataSource) {
		return new DataSourceTransactionManager(dataSource);
	}

	@Bean(name = "mainSqlSessionTemplate")
	public SqlSessionTemplate mainSqlSessionTemplate(@Qualifier("mainSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
		return new SqlSessionTemplate(sqlSessionFactory);
	}

}
